﻿namespace Dissemination.MVC.MVCContrib.Factories
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Web.Mvc;
    using Microsoft.Practices.Unity;
    using System.Web.Routing;
    using MVCContrib.Interfaces;
    using UnityContrib.Interfaces;
    using UnityContrib.Types;
    
    public class CustomControllerFactory : IControllerFactory
    {
        /// <summary>
        /// Gets or sets the container.
        /// </summary>
        /// <value>The container.</value>
        [Dependency]
        public IUnityContainer Container { get; set; }

        /// <summary>
        /// Gets or sets the logger.
        /// </summary>
        /// <value>The logger.</value>
        [Dependency]
        public ILoggerFacade Logger { get; set; }

        /// <summary>
        /// Initializes a new instance of the <see cref="CustomControllerFactory"/> class.
        /// </summary>
        public CustomControllerFactory()
        {

        }

        /// <summary>
        /// Creates the controller.
        /// </summary>
        /// <param name="requestContext">The request context.</param>
        /// <param name="controllerName">Name of the controller.</param>
        /// <returns>The controller.</returns>
        public IController CreateController(RequestContext requestContext, string controllerName)
        {

            Logger.Log("BEFORE CREATE:: CustomControllerFactory.CreateController()", 
                Category.Debug, Priority.None);

            // IControllerFactory without name will return the original 
            // ControllerFactory.  We're going going to let it do it's job
            // and get a reference to the controller.
            IController controller = Container.Resolve<IControllerFactory>()
                .CreateController(requestContext, controllerName);

            Logger.Log(string.Format("AFTER CREATE:: CustomControllerFactory.CreateController() CREATED [{0}]", 
                controller.GetType().Name), Category.Debug, Priority.None);

            return controller;
        }

        /// <summary>
        /// Releases the controller.
        /// </summary>
        /// <param name="controller">The controller.</param>
        public void ReleaseController(IController controller)
        {
            Container.Resolve<IControllerFactory>()
                .ReleaseController(controller);

            Logger.Log(string.Format("CustomControllerFactory.ReleaseController() RELEASED [{0}]",
                controller.GetType().Name), Category.Debug, Priority.None);
        }
    }
}
